#include "map.h"
#include <QGraphicsScene>
#include <QMessageBox>
#include <QDebug>
#include <QWheelEvent>
#include "main_home.h"
#include "algorithm.h"
#include "resultwidget.h"
#include "mainwindow.h"
#include <QDir>
#include <QSet>
#include <cmath>


MapWidget::MapWidget(QWidget *parent) : QWidget(parent), ui(new Ui::MapWidget) {
    ui->setupUi(this);  // 设置UI界面
    userProfileWidget = new UserProfile(this);

    // 查找 map.ui 中的占位组件，并将 UserProfile 界面嵌套到其中
    QVBoxLayout* layout = new QVBoxLayout(ui->userProfileContainer);
    layout->addWidget(userProfileWidget);
    layout->setContentsMargins(0, 0, 0, 0);  // 去掉多余边距

    QString userN = SessionManager::getUsername();
    qDebug()<<userN;
    if (!userN.isEmpty()) {
        userProfileWidget->updateProfile(userN);
    } else {
        qDebug() << "No user is logged in. Skipping profile update.";
    }
    ui->userProfileContainer->setLayout(layout);

    scene = new QGraphicsScene(this);

    QPixmap mapPixmap("C:/Users/LEO/Desktop/study/QT/flights/img/mapa.png");
    if (mapPixmap.isNull()) {
        qWarning("Failed to load map image!");
    }
    mapItem = new QGraphicsPixmapItem(mapPixmap);
    scene->addItem(mapItem);


    ui->graphicsView->setScene(scene);
    ui->graphicsView->setDragMode(QGraphicsView::ScrollHandDrag);  //允许拖拽
    ui->graphicsView->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);  //缩放时以鼠标为中心

    connect(ui->backButton, &QPushButton::clicked, this, &MapWidget::backMain);

    // 初始化城市坐标
    cityCoordinates["北京"] = QPointF(776, 500);
    cityCoordinates["上海"] = QPointF(834, 591);
    cityCoordinates["广州"] = QPointF(764, 669);
    cityCoordinates["成都"] = QPointF(647, 618);
    cityCoordinates["兰州"] = QPointF(662, 574);
    cityCoordinates["乌鲁木齐"] = QPointF(526, 488);
    cityCoordinates["西宁"] = QPointF(646, 561);
    cityCoordinates["台北"] = QPointF(852, 652);
    cityCoordinates["昆明"] = QPointF(669, 694);
    cityCoordinates["西安"] = QPointF(698, 581);
    cityCoordinates["哈尔滨"] = QPointF(825, 416);
    cityCoordinates["拉萨"] = QPointF(546, 639);
    cityCoordinates["首尔"] = QPointF(862, 503);
    cityCoordinates["东京"] = QPointF(963, 468);
    cityCoordinates["马尼拉"] = QPointF(867, 753);
    cityCoordinates["新加坡"] = QPointF(701, 937);
    cityCoordinates["新德里"] = QPointF(412, 642);
    cityCoordinates["曼谷"] = QPointF(652, 813);


    for (auto it = cityCoordinates.begin(); it != cityCoordinates.end(); ++it) {
        addCityMarker(it.key(), it.value());
    }

    // 加载并绘制航线
    loadJourneysFromDatabase();
}


// 添加城市标记的实现
void MapWidget::addCityMarker(const QString &name, const QPointF &position) {
    QGraphicsEllipseItem *marker = new QGraphicsEllipseItem(position.x() - 5, position.y() - 5, 5, 5);
    marker->setBrush(Qt::blue);
    marker->setFlag(QGraphicsItem::ItemIsSelectable);  // 确保标记为可选
    marker->setAcceptHoverEvents(true);  // 接受悬停事件

    marker->setData(0, name);

    scene->addItem(marker);
    cityMarkers.append(marker);

    QGraphicsTextItem *textItem = new QGraphicsTextItem(name);
    textItem->setPos(position.x() + 10, position.y() - 10);
    scene->addItem(textItem);
}


void MapWidget::wheelEvent(QWheelEvent *event) {
    if (event->angleDelta().y() > 0) {
        zoomIn();
    } else {
        zoomOut();
    }
}

void MapWidget::zoomIn() {
    scaleView(1.2);
}

void MapWidget::zoomOut() {
    scaleView(1 / 1.2);
}

void MapWidget::scaleView(qreal scaleFactor) {
    ui->graphicsView->scale(scaleFactor, scaleFactor);
}

void MapWidget::loadJourneysFromDatabase() {
    QSqlDatabase db = AccountManager::getDatabase();
    if (!db.isOpen() && !db.open()) {
        qDebug() << "Failed to open database: " << db.lastError().text();
        return;
    }

    QSqlQuery query(db);
    query.prepare("SELECT j.start_city, j.end_city, fs.from_city, fs.to_city "
                  "FROM journeys j "
                  "JOIN flight_segments fs ON j.journey_id = fs.journey_id");

    if (!query.exec()) {
        qDebug() << "Failed to load journey segments: " << query.lastError().text();
        return;
    }

    // 用于记录每条线路的偏移索引
    QMap<QString, int> connectionOffsetMap;

    // 遍历查询结果
    while (query.next()) {
        QString startCity = query.value(0).toString();  // journey 起点城市
        QString endCity = query.value(1).toString();    // journey 终点城市
        QString fromCity = query.value(2).toString();   // segment 起点城市
        QString toCity = query.value(3).toString();     // segment 终点城市

        QString connectionKey = fromCity + "->" + toCity;

        // 获取偏移索引
        int offsetIndex = connectionOffsetMap.value(connectionKey, 0);
        connectionOffsetMap[connectionKey] = offsetIndex + 1;

        // 绘制曲线
        if (cityCoordinates.contains(fromCity) && cityCoordinates.contains(toCity)) {
            drawArcConnection(fromCity, toCity, Qt::blue, offsetIndex);  // 使用偏移索引
        } else {
            qDebug() << "One of the cities is missing in the map: " << fromCity << " or " << toCity;
        }
    }
}


void MapWidget::drawArcConnection(const QString &fromCity, const QString &toCity, const QColor &color, int offsetIndex) {
    QPointF fromPos = cityCoordinates.value(fromCity);
    QPointF toPos = cityCoordinates.value(toCity);

    // 计算控制点，偏移用于创建弧线
    QPointF midPoint = (fromPos + toPos) / 2;
    QPointF direction = toPos - fromPos;
    QPointF perpendicular(-direction.y(), direction.x());  // 垂直方向
    perpendicular = perpendicular / std::sqrt(perpendicular.x() * perpendicular.x() + perpendicular.y() * perpendicular.y());  // 单位化
    QPointF controlPoint = midPoint + perpendicular * (30.0 * offsetIndex);  // 偏移控制点

    // 创建贝塞尔曲线
    QPainterPath path(fromPos);
    path.quadTo(controlPoint, toPos);

    // 绘制曲线
    QGraphicsPathItem *arc = new QGraphicsPathItem(path);
    QPen pen(color, 2);
    arc->setPen(pen);
    scene->addItem(arc);
}



void MapWidget::updateMapConnections() {
    // 清空现有的连线
    if (userProfileWidget) {
        QString userN = SessionManager::getUsername();

        userProfileWidget->updateProfile(userN);
        ui->userProfileContainer->update();
        qDebug()<<"userInfoupdated";
    }
    QList<QGraphicsItem*> lines = scene->items();
    for (QGraphicsItem* item : lines) {
        if (dynamic_cast<QGraphicsLineItem*>(item)) {
            scene->removeItem(item);
        }
    }
    // 重新加载数据库中的航线
    loadJourneysFromDatabase();
    qDebug() << "Map connections updated.";

    scene->update();
    ui->graphicsView->viewport()->update();
    qDebug() << "Map connections updated.";
}


